package com.example.video.util.websocket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

public class WebSocketService extends WebSocketClient {

    private CountDownLatch latch;
    private String message;
    private String result;

    public CountDownLatch getLatch() {
        return latch;
    }

    public String getMessage() {
        return message;
    }

    public String getResult() {
        return result;
    }

    public WebSocketService(String url, String message) throws URISyntaxException {
//        super(new URI("ws://localhost:8080/socket"));
        super(new URI(url));
        this.latch = new CountDownLatch(1);
        this.message = message;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        // 发送数据
        send(this.message);
    }

    @Override
    public void onMessage(String message) {
        this.result = message;
        // 减少 latch 计数
        latch.countDown();
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        // 关闭连接
        close();
    }

    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }

    public static String sendCmd(String url,String message) throws URISyntaxException, InterruptedException {
            // 使用 CountDownLatch 等待响应
            WebSocketService client = new WebSocketService(url, message);
            client.connect(); // 连接服务器
            client.getLatch().await(); // 等待响应
            client.close();
            return client.getResult();
    }
}